<?php
/**
 * Created by PhpStorm.
 * User: PC
 * Date: 2017/3/7
 * Time: 11:06
 */
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
use Common\Model\NewsModel;
use Think\Model;

class VoteController extends AdminbaseController
{
    public function index(){
        $vote_count = M('vrnews1.vote')->count();
        $page = $this->page($vote_count, 20);
        $show = $page->show('Admin');

        if(I('vote_name')){
            $where = array('title'=>array('like', '%'.I('vote_name').'%'), 'status'=>1);
        }else{
            $where = array('status'=>1);
        }
        $vote_list  = M('vrnews1.vote')->where($where)->order('create_time DESC')->limit($page->firstRow.','.$page->listRows)->select();

        $this->assign('vote_domain', C('vote_domain'));
        $this->assign('page', $show);
        $this->assign('list', $vote_list);
        $this->display();
    }

    public function addVote(){
        $vote_id = I('get.id');

        if(IS_POST){
            $vote_model = M('vrnews1.vote');

            if(is_array($_POST['zhuban_name']) && count($_POST['zhuban_name']) > 0){
                foreach($_POST['zhuban_name'] as $k=>$v){
                    if($v != ''){
                        $zhuban_name[] = $v;
                    }
                }
            }
            if(is_array($_POST['chengban_name']) && count($_POST['chengban_name']) > 0){
                foreach($_POST['chengban_name'] as $k=>$v){
                    if($v != ''){
                        $chengban_name[] = $v;
                    }
                }
            }
            if(is_array($_POST['vote']) && count($_POST['vote']) > 0){
                foreach($_POST['vote'] as $k=>$v){
                    if($v != ''){
                        $vote[] = $v;
                    }
                }
            }
            if(is_array($_POST['group']) && count($_POST['group']) > 0){
                foreach($_POST['group'] as $k=>$v){
                    if($v != ''){
                        $group[] = $v;
                    }
                }
            }

            if(!I('title', 0)) $this->error('请填写投票标题');
            if(!I('vote_num', 0)) $this->error('请填写投票次数');
            if(!$_FILES['imageFile']['name'] && I('cover_image',0)) $this->error('请上传封面图');
            if(!I('abstract', 0)) $this->error('请填写投票摘要');
            if(!I('start_time', 0)) $this->error('请选择开始时间');
            if(!I('end_time', 0)) $this->error('请选择结束时间');
            if(!$group) $this->error('请添加组');

            $vote_data = array(
                'title'    => I('title', ''),
                'vote_num' => I('vote_num', 0),
                'huiwenbi' => I('huiwenbi', 0),
                'abstract' => I('abstract', ''),
                'start_time' => strtotime(I('start_time', 0)),
                'end_time' => strtotime(I('end_time', 0)),
                'host' => serialize($zhuban_name),
                'contractors' => serialize($chengban_name),
                'vote' => serialize($vote),
                'type' => I('type', 0),
                'status'   => 1,
                'create_time' => time(),
            );

            if($_FILES['imageFile']['name']){
                $news_model = new NewsModel();  //上传封面图
                $image_url = $news_model->uploadImage();
                $vote_data['cover_image'] = $image_url;
            }else{
                $vote_data['cover_image'] = I('img_url');
            }

            $group_arr = I('post.group', '');
            $vote_class = M('vrnews1.vote_class');

            if($vote_id){
                $ret = $vote_model->where(array('vote_id'=>$vote_id))->save($vote_data);
                if($group_arr && $ret){
                    foreach($group_arr as $key=>$val){
                        $exist = $vote_class->where(array('class_id'=>$key, 'parent_id'=>0))->find();
                        if($exist){
                            $vote_class->where(array('vote_id'=>$vote_id, 'parent_id'=>0, 'class_id'=>$key))->save(array('class_name'=>$val));
                        }else{
                            $vote_class->add(array('vote_id'=>$vote_id, 'parent_id'=>0, 'class_name'=>$val, 'create_time'=>time()));
                        }
                    }
                }
            }else{
                $ret = $vote_model->add($vote_data);
                $vote_id = $vote_model->getLastInsID();

                if($group_arr && $ret){
                    foreach($group_arr as $key=>$val){
                        $vote_class->add(array('vote_id'=>$vote_id, 'class_name'=>$val, 'create_time'=>time()));
                    }
                }
            }

            if($ret){
                $this->redirect(U('Vote/addClass', array('id'=>$vote_id)));
            }else{
                $this->error('操作失败');
            }
            exit();
        }

        if($vote_id){
            $vote_info = M('vrnews1.vote')->where(array('vote_id'=>$vote_id))->find();
            $vote_info['host'] = unserialize($vote_info['host']);
            $vote_info['contractors'] = unserialize($vote_info['contractors']);
            $vote_info['vote'] = unserialize($vote_info['vote']);

            $all_group = M('vrnews1.vote_class')->where(array('vote_id'=>$vote_id, 'parent_id'=>0))->select();
            $this->assign('all_group', $all_group);
            $this->assign('news_info', $vote_info);
        }
        $this->display();
    }

    public function addClass(){
        $vote_class_model = M('vrnews1.vote_class');
        $vote_id = I('id');

        if(IS_POST){
            $vote_class_arr = I('vote_class', 0);
            $parent_id_arr  = I('parent_id', 0);

            if(!I('edit', 0)){
                foreach($vote_class_arr as $key=>$val){
                    $vote_class_model->add(array('vote_id'=>$vote_id, 'parent_id'=>$parent_id_arr[$key], 'class_name'=>$val, 'create_time'=>time()));
                }
            }else{
                foreach($vote_class_arr as $key=>$val){
                    $vote_class_model->where(array('vote_id'=>$vote_id, 'class_id'=>$key))->save(array('class_name'=>$val, 'parent_id'=>$parent_id_arr[$key]));
                }
//                $this->redirect(U('vote/index'));
            }

            $this->redirect(U('vote/addOption', array('id'=>$vote_id)));
        }

        $get_all_class = $this->getAllClass($vote_id);
        $_arr = $get_all_class['_arr'];
        $group_arr = $get_all_class['group_arr'];

        $this->assign('info', $_arr);
        $this->assign('group_arr', $group_arr);
        $this->display();
    }

    public function addOption(){
        $vote_class_model = M('vrnews1.vote_class');
        $vote_id = I('id', 1);

        if(IS_POST){
            $vote_option_model = M('vrnews1.vote_option');
            $name_arr = I('name', array());

            if($_FILES['imageFile']['name'][0]){
                $news_model = new NewsModel();  //上传封面图
                $image_url = $news_model->uploadImage();
            }

            //取出最大的number
            $vote_info = M('vrnews1.vote_option')->field(['vote_id, number'])->where(array('vote_id'=>$vote_id))->select();

            if($vote_info){
                $max_number = end($vote_info)['number'] + 1;
            }else{
                $max_number = 1;
            }

            foreach($name_arr as $k=>$v){
                if($v == '') continue;
                $option_data['cover_image'] = $image_url[$k];
                $option_data['vote_id']  = $vote_id;
                $option_data['group_id'] = $_POST['group_id'][$k];
                $option_data['class_id'] = $_POST['class_id'][$k];
                $option_data['name']     = $_POST['name'][$k];
                $option_data['number']   = $max_number;
                $option_data['abstract'] = serialize($_POST['abstract'][$k]);
                $option_data['create_time'] = time();

                $res = $vote_option_model->add($option_data);
                $max_number += 1;
            }

            if($res !== false){
                $this->redirect(U('vote/addOption', array('id'=>$vote_id)));
            }else{
                $this->error('添加异常');
            }
            exit();
        }

        $all_group = $vote_class_model->where(array('vote_id'=>$vote_id, 'parent_id'=>0))->select();

        $this->assign('all_group', $all_group);
        $this->display();
    }

    public function options(){
        $vote_id = I('id', 0);
        $vote_option_model = M('vrnews1.vote_option');

        $option_count = $vote_option_model->where(array('vote_id'=>$vote_id))->count();
        $page = $this->page($option_count, 20);

        $list = $vote_option_model->where(array('vote_id'=>$vote_id))->limit($page->firstRow.','.$page->listRows)->select();

        $this->assign('page', $page->show('Admin'));
        $this->assign('list', $list);
        $this->display();
    }

    public function editOption(){
        $option_id = I('option_id', 0);
        $vote_id   = I('vote_id', 0);
        $vote_option_model = M('vrnews1.vote_option');

        if(IS_POST){
            if($_FILES['imageFile']['name'][0]){
                $news_model = new NewsModel();  //上传封面图
                $image_url = $news_model->uploadImage();
                $option_data['cover_image'] = $image_url;
            }else{
                $option_data['cover_image'] = I('img_url');
            }

            $option_data['group_id'] = I('group_id', 0);
            $option_data['class_id'] = I('class_id', 0);
            $option_data['name'] = I('name', '');
            $option_data['abstract'] = serialize(I('abstract'));
            $option_id = $option_id ? $option_id : trim($_GET['option_id']);

            $ret = $vote_option_model->where(array('option_id'=>$option_id))->save($option_data);

            if($ret !== false){
                $vote_id = $vote_id ? $vote_id : $_GET['vote_id'];
                $this->success('修改成功', U('vote/options', array('id'=>$vote_id)));
                exit();
            }
            $this->error('修改失败');
            exit();
        }

        $option_info = $vote_option_model
            ->alias('vo')
            ->field('vo.option_id, vo.vote_id, vo.group_id, vo.class_id, vo.name, vo.abstract, vo.cover_image, vc.class_name')
            ->join('left join vrnews1.vote_class as vc ON vo.group_id=vc.class_id')
            ->where(array('vo.option_id'=>$option_id))->find();

        $all_group = M('vrnews1.vote_class')->where(array('vote_id'=>$vote_id, 'parent_id'=>0))->select();

        $all_class_sql = "SELECT * FROM vrnews1.vote_class WHERE  parent_id = (SELECT group_id FROM vrnews1.vote_option WHERE option_id=$option_id LIMIT 1)";
        $all_class = $vote_option_model->query($all_class_sql);

        $option_info['abstract'] = $option_info['abstract'] ? unserialize($option_info['abstract']) : '';

        $this->assign('all_class', $all_class);
        $this->assign('all_group', $all_group);
        $this->assign('info', $option_info);
        $this->display();
    }

    public function VoteDel(){
        $vote_model = M('vrnews1.vote');
        $news_checkbox_ids = implode(',',I("news_checbox"));
        $where['vote_id'] = array('IN',$news_checkbox_ids);

        echo $vote_model->where($where)->save(array('status'=>0));
        exit();
    }

    public function addOneOptions(){
        $vote_id = I('vote_id', 0);
        $vote_option_model = M('vrnews1.vote_option');
        if(!$vote_id) $this->error('投票ID错误');

        if(IS_POST){
            $abstract = I('abstract', '');

//            if(!I('name', 0)) $this->error('请填写名称');
//            if(!$abstract[0]) $this->error('请填写简介');

            if($_FILES['imageFile']['name']){
                $news_model = new NewsModel();  //上传封面图
                $image_url = $news_model->uploadImage();
            }

            //取出最大的number
            $vote_info = M('vrnews1.vote_option')->field(['vote_id, number'])->where(array('vote_id'=>$vote_id))->select();

            if($vote_info){
                $max_number = end($vote_info)['number'] + 1;
            }else{
                $max_number = 1;
            }

            $option_data = array(
                'vote_id'  => I('vote_id'),
                'group_id' => I('group_id', 0),
                'class_id' => I('class_id', 0),
                'cover_image' => $image_url ? $image_url : '',
                'name'        => I('name', ''),
                'abstract'    => serialize(I('abstract', '')),
                'number'      => $max_number,
                'create_time' => time(),
            );

            $ret = M('vrnews1.vote_option')->add($option_data);
            if($ret){
                $this->redirect(U('vote/options', array('id'=>$vote_id)));
                exit();
            }
            $this->error('添加失败');
        }

        $group_arr = M('vrnews1.vote_class')->where(array('vote_id'=>$vote_id, 'parent_id'=>0))->select();

        $this->assign('all_group', $group_arr);
        $this->display();
    }

    public function delGroup(){
        if(IS_POST){
            $class_id = I('id', 0, 'intval');
            if(!$class_id) $this->ajaxReturn('参数错误');
            $ret = M('vrnews1.vote_class')->where(array('class_id'=>$class_id))->delete();
            if($ret){
                exit(json_encode(array('code'=>200)));
            }else{
                exit(json_encode(array('code'=>151, 'msg'=>'error')));
            }
        }
    }

    public function getClass(){
        $pid = I('pid', 0);
        if(!$pid) exit();
        $class_list = M('vrnews1.vote_class')->where(array('parent_id'=>$pid))->select();
        $return_data = json_encode($class_list, JSON_FORCE_OBJECT);
        echo $return_data;
    }

    public function Statistical(){
        $vote_id = I('id', 0, 'intval');
        $sort    = I('sort', 0, 'intval');

        if(!$vote_id) $this->error('参数错误');

        if(!$sort){
            $order = 'ballot_count DESC';
        }else{
            $order = 'ballot_count ASC';
        }

        $vote_info = M('vrnews1.vote')->alias('v')->field('v.title, COUNT(b.ballot_id) as ballot_count')->join('vrnews1.vote_ballot as b ON v.vote_id=b.vote_id', 'left')->where(array('v.vote_id'=>$vote_id))->find();

        $list = M('vrnews1.vote_ballot')->alias('b')
            ->field('c.class_name as group_name, c1.class_name as class_name, o.`name`, COUNT(b.ballot_id) as ballot_count')
            ->join('vrnews1.vote_option o ON b.option_id=o.option_id', 'left')
            ->join('vrnews1.vote_class c ON o.group_id=c.class_id', 'left')
            ->join('vrnews1.vote_class c1 ON o.class_id=c1.class_id', 'left')
            ->where("b.vote_id={$vote_id}")
            ->group('b.option_id')
            ->select();

        $ballot_count = count($list);
        $page = $this->page($ballot_count, 20);

        $list = M('vrnews1.vote_ballot')->alias('b')
            ->field('c.class_name as group_name, c1.class_name as class_name, o.`name`, COUNT(b.ballot_id) as ballot_count')
            ->join('vrnews1.vote_option o ON b.option_id=o.option_id', 'left')
            ->join('vrnews1.vote_class c ON o.group_id=c.class_id', 'left')
            ->join('vrnews1.vote_class c1 ON o.class_id=c1.class_id', 'left')
            ->where("b.vote_id={$vote_id}")
            ->group('b.option_id')
            ->order($order)
            ->limit($page->firstRow.','.$page->listRows)
            ->select();

        $this->assign('list', $list);
        $this->assign('page', $page->show('Admin'));
        $this->assign('vote_info', $vote_info);
        $this->display();
    }

    public function ExportExcel(){
        $vote_id = I('id', 0, 'intval');
        if(!$vote_id) $this->error('参数错误');
        vendor('PHPExcel.PHPExcel');//导入类库

        $datas = M('vrnews1.vote_ballot')->alias('b')
            ->field('c.class_name as group_name, c1.class_name as class_name, o.`name`, COUNT(b.ballot_id) as ballot_count')
            ->join('vrnews1.vote_option o ON b.option_id=o.option_id', 'left')
            ->join('vrnews1.vote_class c ON o.group_id=c.class_id', 'left')
            ->join('vrnews1.vote_class c1 ON o.class_id=c1.class_id', 'left')
            ->where("b.vote_id={$vote_id}")
            ->group('b.option_id')
            ->order('ballot_count DESC')
            ->select();

        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->getProperties()->setTitle("投票统计");
        $objPHPExcel->getProperties()->setCreator("xinhuiwen")->setLastModifiedBy("xinhuiwen")->setTitle("xinhuiwen")->setSubject("xinhuiwen")->setDescription("xinhuiwen")->setKeywords("xinhuiwen")->setCategory("xinhuiwen");
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '姓名')->setCellValue('B1', '所在组')->setCellValue('C1', '所在类')->setCellValue('D1', '总票数');
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(24);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(24);

        foreach($datas as $key=>$value){
            $i = $key + 2;
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$i,  $value['name']);//这里是设置A1单元格的内容
            $objPHPExcel->getActiveSheet()->setCellValue('B'.$i,  $value['group_name']);////这里是设置B1单元格的内容
            $objPHPExcel->getActiveSheet()->setCellValue('C'.$i,  $value['class_name']);////这里是设置B1单元格的内容
            $objPHPExcel->getActiveSheet()->setCellValue('D'.$i,  $value['ballot_count']);////这里是设置B1单元格的内容
        }

        $objActSheet = $objPHPExcel->getActiveSheet();
        $filename = '投票统计';
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save('php://output');
    }

    public function delOption()
    {
        $option_id = I('option_id', 0, 'intval');

        if(!$option_id){exit(json_encode(array('code'=>0, 'msg'=>'参数错误')));}

        $ret = M('vrnews1.vote_option')->where(array('option_id'=>$option_id))->delete();

        if($ret !== false){
            $return_data = array('code'=>1, 'msg'=>'');
        }else{
            $return_data = array('code'=>0, 'msg'=>'删除失败');
        }

        exit(json_encode($return_data));
    }

    protected function getAllClass($vote_id){
        $vote_class_model = M('vrnews1.vote_class');

        $group_arr = array();

        $class_arr = $vote_class_model->alias('vc1')->field('vc1.class_id, vc1.vote_id, vc1.parent_id,vc1.class_name')->join('LEFT JOIN vrnews1.vote_class as vc2 ON vc1.class_id=vc2.parent_id')->where(array('vc1.vote_id'=>$vote_id))->group('vc1.class_id')->select();

        foreach($class_arr as $key=>$val){
            if($val['parent_id'] == 0){
                $group_arr[] = $val;
            }
        }

        $_arr = array();
        foreach($group_arr as $key=>$group){
            foreach($class_arr as $k=>$class){
                if($group['class_id'] == $class['parent_id']){
                    $_arr[$k]['vote_id'] = $group['vote_id'];
                    $_arr[$k]['class_id'] = $class['class_id'];
                    $_arr[$k]['parent_id'] = $class['parent_id'];
                    $_arr[$k]['group_name'] = $group['class_name'];
                    $_arr[$k]['class_name'] = $class['class_name'];
                }
            }
        }

        return array('_arr'=>$_arr, 'group_arr'=>$group_arr);
    }

    protected function mb_unserialize($serial_str) {
        $serial_str= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
        $serial_str= str_replace("\r", "", $serial_str);
        return unserialize($serial_str);
    }


    public function editData(){
        $vote_id = I('vote_id', 0, 'intval');
        $start_num = 127;

        if(!$vote_id){return 'error';}

        $all_option = M('vrnews1.vote_option')->where(array('vote_id'=>$vote_id, 'number'=>$start_num))->select();

        if(!$all_option){return 'error2';}

        $vote_option_model = M('vrnews1.vote_option');

        $number = 0;

        foreach ($all_option as $key=>$val){
            $vote_option_model->where(array('option_id'=>$val['option_id'], 'vote_id'=>$val['vote_id']))->save(array('number'=>$val['number']+$number));
            if($vote_option_model === false){
                exit($val['option_id']);
            }
            $number++;
        }

        echo 'ok, total:'.$number;
    }
}